class_name Monster
extends CharacterBody2D
@export var active_time = 2.0
@export var speed:float = 200.0
@onready var sprite := $Sprite2D
enum STATE{
	UNFIND,
	ACTIVE,
	RUN,
	BUBBLIZE,
	DEFEAT_EARTH,
	DEFEAT_SEA
}

var state =STATE.UNFIND
var active_value = 0.0
var run_path = []
var gems = []
var is_alive:bool = true
var copy:Sprite2D = null

func _ready() -> void:
	#sprite.material.set_shader_parameter("delta",0.0)
	sprite.material = sprite.material.duplicate()

func append_gem(p_gem):
	gems.push_back(p_gem)

func _process(delta: float) -> void:
	if is_instance_valid(copy):
		copy.global_transform = sprite.global_transform
	match state:
		STATE.ACTIVE:
			if active_value == 0.0 :
				copy = $Sprite2D.duplicate()
				copy.material = sprite.material
				CellManager.sub_view.add_child(copy)
				pass
			active_value+=delta
			if active_time < active_value:
				state = STATE.RUN
				run_path = get_run_path()
			sprite.material.set_shader_parameter("delta",active_value)
		STATE.RUN:
			if run_path.is_empty():
				state = STATE.BUBBLIZE
				$CollisionShape2D.set_deferred("disabled",true)
				$CollisionShape2D2.set_deferred("disabled",false)
				$bubble.show()
				run_path.append(CellManager.get_random_point())
				return
			var target_pos:Vector2 = run_path[0]
			global_position += (target_pos-global_position).normalized()*delta*speed
			if(global_position-target_pos).length()<10:
				run_path.pop_front()
		STATE.BUBBLIZE:
			if run_path.is_empty():
				global_position += Vector2.UP*0.5*delta*speed
				return
			var target_pos:Vector2 = run_path[0]
			global_position += (target_pos-global_position).normalized()*delta*speed
			if(global_position-target_pos).length()<10:
				run_path.pop_front()

func die():
	is_alive = false
	queue_free()
	if state == STATE.RUN:
		for i in gems:
			i.change_state_to_fly_to_valve()
	else:
		for i in gems:
			i.state= Gem.STATE.SCORE
			i.queue_free()

func get_run_path():
	var ret = []
	ret.push_back(CellManager.valve.global_position)
	return ret

func _on_area_2d_body_entered(body: Node2D) -> void:
	if state == STATE.UNFIND:
		if body is Monster && body != self &&body.state==STATE.RUN:
			self.state = STATE.ACTIVE
		elif body is Player:
			body.晕了()
			self.state = STATE.ACTIVE
			


func _on_area_2d_area_entered(area: Area2D) -> void:
	if state == STATE.UNFIND:
		if area is Equipment && area.type == Equipment.TOOL.SHOVEL:
			self.state = STATE.ACTIVE
			area.player.晕了()
